package com.yand.disk.demo.controller;


import com.github.pagehelper.PageInfo;
import com.yand.disk.demo.entity.TDownLink;
import com.yand.disk.demo.entity.TFileInfo;
import com.yand.disk.demo.entity.common.Result;
import com.yand.disk.demo.entity.dto.FileLinkDto;
import com.yand.disk.demo.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.security.NoSuchAlgorithmException;


/**
 * 文件控制器类
 */
@RestController
public class FileInfoController {


    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 跳转文件列表页面
     * @return
     */
    @GetMapping("file/list")
    public ModelAndView toPage(TFileInfo fileInfo, Model model){
        //查询出当前的所有的文件列表
        PageInfo<TFileInfo> fileInfoPageInfo = fileInfoService.queryFileList(fileInfo);
        model.addAttribute("pageInfo", fileInfoPageInfo);
        //跳转文件列表页面
        ModelAndView modelAndView = new  ModelAndView();
        modelAndView.setViewName("/file-list");
        return modelAndView;
    }

    /**
     * 跳转文件新增/修改页面
     * @param fileId
     * @param fileInfo
     * @return
     */
    @GetMapping("file/input/{fileId}")
    public ModelAndView toAddPage(@PathVariable(value = "fileId") Integer fileId, TFileInfo fileInfo){
        ModelAndView modelAndView = new  ModelAndView();
        String typeSuffix = (fileId == 0) ? "input":"edit";
        //如果是文件修改的话则获取该文件
        if("edit".equals(typeSuffix)){

        }
        modelAndView.setViewName("/file-"+typeSuffix);
        return modelAndView;
    }


    /**
     *
     * @param fileIds 页面传回的fileids 用逗号拼接
     * @return
     */
    @GetMapping("file/link")
    public ModelAndView createLink(@RequestParam(value = "fileIds") String fileIds, Model model){


        model.addAttribute("fileIds",fileIds);
        ModelAndView modelAndView = new  ModelAndView();

        modelAndView.setViewName("/link-input");
        return modelAndView;
    }


    /**
     * 创建连接
     * @param fileLinkDto
     * @return
     */
    @PostMapping("file/link")
    public Result createLink(FileLinkDto fileLinkDto){
        TDownLink link = null;
        String mesage = "";
        try {
            link =  fileInfoService.createFileLink(fileLinkDto);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Result result = new Result(0);
        mesage = "下载链接为："+link.getLinkUrl();
        if("0".equals(link.getIscode())){
            mesage += ", 提取码:"+link.getIdentifyingcode();
        }
        result.setMessage(mesage);
        return result;
    }





}
